package com.qsboss.demo.controller;

import com.qsboss.demo.domain.Result;
import com.qsboss.demo.pojo.TbUser;
import com.qsboss.demo.service.TbUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 军哥
 * @version 1.0
 * @description: 用户信息控制类
 * @date 2023/10/22 16:20
 */

@Controller
@Slf4j
@RequestMapping(value = "/user")
public class TbUserController {

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    TbUserService tbUserService;

    @Autowired
    HttpServletRequest httpServletRequest;

    @PostMapping(value = "/login")
    @ResponseBody
    public Result login(String userName, String userPass) {
        Result result = tbUserService.login(userName, userPass);

        if(result.getCode() == 200) {
            HttpSession session = httpServletRequest.getSession();
            session.setAttribute("user", result.getData());
        }

        return result;
    }

    @PostMapping(value = "/loginOut")
    @ResponseBody
    public Result loginOut() {
        HttpSession session = httpServletRequest.getSession();

        session.removeAttribute("user");

        return Result.SUCCESS();
    }

    @PostMapping(value = "/sendMail")
    @ResponseBody
    public Result sendMail(String userEmail) {
        System.out.println("发送密码邮件~~~~~");

        //-- 根据邮件查找用户密码
        TbUser tbUser = tbUserService.getUserByMail(userEmail);
        if(tbUser == null) {
            return Result.FAILED(404, "用户不存在");
        }

        //-- 邮件发送密码
        try {
            //-- 创建邮件对象
            MimeMessage message = javaMailSender.createMimeMessage();

            //-- 创建helper
            MimeMessageHelper helper = new MimeMessageHelper(message);

            //-- 设置邮件的内容
            helper.setFrom("3350996729@qq.com");
            helper.setTo(userEmail);
            String title = "尊敬的" + tbUser.getNickName() + "用户，找回密码邮件。";
            helper.setSubject(title);
            String body = "您的账号是：" + tbUser.getUserName() + "<br>您的密码是：" + tbUser.getUserPass() + "<br>";
            helper.setText(body);

            //-- 发送邮件
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            return Result.FAILED(500, "发送未知错误");
        } finally {
        }

        return Result.SUCCESS();
    }

}
